package com.star95.shirologin.controller;

import com.star95.shirologin.common.constants.CommonConstants;
import com.star95.shirologin.common.util.JwtUtil;
import com.star95.shirologin.common.util.RedisUtil;
import com.star95.shirologin.common.util.UserUtil;
import com.star95.shirologin.dto.CustomerUserDto;
import com.star95.shirologin.dto.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 客户端接口
 */
@Slf4j
@RestController
@RequestMapping("/customer")
@Api(tags = "客户端接口")
public class CustomerController {
    @Autowired
    private RedisUtil redisUtil;

    @ApiOperation("登录接口")
    @PostMapping("/login")
    public Result<CustomerUserDto> login(@Validated @RequestBody CustomerUserDto customerUserDto) {
        log.info("客户端登录请求参数，customerUserDto:{}", customerUserDto);
        //1. 校验用户是否有效
        CustomerUserDto customerUserDto1 = UserUtil.customerUserDtoMap.get(customerUserDto.getCustomerAccount());
        if (Objects.isNull(customerUserDto1)) {
            log.info("用户登录失败，用户不存在！");
            return Result.error("用户不存在");
        }
        //2. 校验用户名或密码是否正确
        if (!customerUserDto1.getPassword().equals(customerUserDto.getPassword())) {
            log.info("密码不正确，customerAccount:{}", customerUserDto1.getCustomerAccount());
            return Result.error("用户名或密码错误");
        }
        //用户登录信息
        log.info("用户账号: {},登录成功！", customerUserDto1.getCustomerAccount());
        String username = customerUserDto1.getCustomerAccount();
        String syspassword = customerUserDto1.getPassword();
        //1.生成token
        String token = JwtUtil.sign(username, syspassword);
        // 设置token缓存有效时间
        redisUtil.set(CommonConstants.PREFIX_USER_TOKEN + token, token, TimeUnit.SECONDS, JwtUtil.EXPIRE_TIME * 2);
        customerUserDto1.setToken(token);
        return Result.ok(customerUserDto1);
    }

    @ApiOperation("查询用户余额接口")
    @PostMapping("/balance")
    public Result<Double> customerList() {
        log.info("客户端请求查询用户余额接口");
        return Result.ok(9999.99d);
    }
}
